package com.ithaipeng.redanttakeaway.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ithaipeng.redanttakeaway.exception.CustomException;
import com.ithaipeng.redanttakeaway.mapper.OrdersMapper;
import com.ithaipeng.redanttakeaway.pojo.*;
import com.ithaipeng.redanttakeaway.service.*;
import com.ithaipeng.redanttakeaway.tools.BaseContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Service
@Transactional
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements IOrdersService {
    @Autowired
    private IShoppingCartService shoppingCartService;
    @Autowired
    private IUserService userService;
    @Autowired
    private IAddressBookService addressBookService;
    @Autowired
    private IOrderDetailService orderDetailService;
    @Override
    public void submit(Orders orders) {
        //先创建订单号！
        long id = IdWorker.getId();
        //再获取用户id
        orders.setUserId(BaseContext.getCurrentId());
        //获取用户购物车数据
        LambdaQueryWrapper<ShoppingCart> shoppingCartLambdaQueryWrapper=new LambdaQueryWrapper<>();
        shoppingCartLambdaQueryWrapper.eq(orders.getUserId()!=null,ShoppingCart::getUserId,orders.getUserId());
        List<ShoppingCart> shoppingCartList = shoppingCartService.list(shoppingCartLambdaQueryWrapper);
        if(shoppingCartList.isEmpty()){
            //说明购物车为空，并抛出异常业务线!
            throw new CustomException("目前您的购物车为空，快去添加吧！");
        }
        //查询用户信息
        User user = userService.getById(orders.getUserId());
        //获取下单信息，一定是，默认地址!
        AddressBook addressBook = addressBookService.getById(orders.getAddressBookId());
        if(addressBook==null){
            throw new CustomException("地址有误!，不能下单！");
        }
        AtomicInteger amount=new AtomicInteger();
        List<OrderDetail> orderDetailList = shoppingCartList.stream().map((item) -> {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(id);
            orderDetail.setNumber(item.getNumber());
            orderDetail.setDishId(item.getDishId());
            orderDetail.setDishFlavor(item.getDishFlavor());
            orderDetail.setSetmealId(item.getSetmealId());
            orderDetail.setName(item.getName());
            orderDetail.setImage(item.getImage());
            orderDetail.setAmount(item.getAmount());
            amount.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());
            return orderDetail;
        }).collect(Collectors.toList());
        orders.setId(id);
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setStatus(2);
        orders.setAmount(new BigDecimal(amount.get()));
        orders.setNumber(String.valueOf(id));//订单号
        orders.setUserName(user.getName());
        orders.setConsignee(addressBook.getConsignee());
        orders.setPhone(addressBook.getPhone());
        orders.setAddress((addressBook.getProvinceName()==null?"": addressBook.getProvinceName())
                +(addressBook.getCityName()==null?"":addressBook.getCityName())
                +(addressBook.getDistrictName()==null?"":addressBook.getDistrictName())
                +(addressBook.getDetail()==null?"":addressBook.getDetail()));
        this.save(orders);
        //再向订单明细表插入数据多条!
        orderDetailService.saveBatch(orderDetailList);
        //插入成功后,清空购物车!
        shoppingCartService.remove(shoppingCartLambdaQueryWrapper);
    }
}
